import React, { useEffect, useState } from 'react'
import { Modal, Form, Input, Space, Button } from 'antd'
import { PrimaryButton, ViceButton } from '@components/XButton'
import style from './Index.module.less'
import classNames from 'classnames'

const { Item } = Form

// 渲染人员列表
function renderList (list = [], type, formRef, setIndex, setVisible) {
  const Btn = type === '申请人' ? PrimaryButton : ViceButton
  return list.map((li, i) => {
    const disable = li.status === 0
    const s = classNames({ [style['text-disabled']]: disable })
    const ClickHandle = () => {
      formRef.setFieldsValue({ name: li })
      setIndex(i)
      setVisible(true)
    }
    return (
      <Btn key={i} onClick={ClickHandle}>
        <span className={s}>{li}</span>
      </Btn>
    )
  })
}

function Main ({ value, type, onChange }) {
  const Btn = type === '申请人' ? PrimaryButton : ViceButton
  const [visible, setVisible] = useState(false)
  const [formRef] = Form.useForm()
  const [index, setIndex] = useState(-1)
  const [list, setList] = useState([])
  useEffect(() => {
    if (typeof value === 'string' && value.length > 0) {
      setList(value.split(','))
    } else {
      setList([])
    }
  }, [value])
  return (
    <div className={style.container}>
      <Modal
        title={index !== -1 ? `编辑${type}` : `添加${type}`} open={visible} onCancel={() => setVisible(false)}
        footer={
          <Space>
            {index !== -1 && (
              <Button
                type='ghost' danger
                onClick={() => {
                  const l = [...list]; l.splice(index, 1); onChange(l.join()); setVisible(false); setIndex(-1)
                }}
              >删除
              </Button>
            )}
            <Button onClick={() => { setVisible(false); setIndex(-1) }}>取消</Button>
            <Button type='primary' onClick={() => formRef.submit()}>确定</Button>
          </Space>
        }
      >
        <Form
          form={formRef} labelCol={{ flex: '80px' }} onFinish={d => {
            const l = [...list]
            if (index === -1) {
              l.push(d.name)
            } else {
              l.splice(index, 1, d.name)
            }
            onChange(l.join())
            setVisible(false)
            setIndex(-1)
          }}
        >
          <Item name='name' label='姓名' rules={[{ required: true, message: '姓名不能为空' }]}>
            <Input placeholder='请输入' allowClear />
          </Item>
        </Form>
      </Modal>
      {renderList(list, type, formRef, setIndex, setVisible)}
      <Btn type='dashed' onClick={() => { setVisible(true); setIndex(-1); formRef.resetFields() }}>+添加</Btn>
    </div>
  )
}

export default Main
